﻿using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MyCommon.Helper;
using MyCommon.HttpContextUser;
using MyExtension.Authorizations;
using MyIServices;
using MyModels;
using MyModels.Models;
using MyModels.ViewModels;
using SqlSugar;

namespace MyApi.Controllers
{
    /// <summary>
    /// 授权控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize("Permission")]
    public class PermissionController : BaseApiController
    {
        private readonly IHttpContextAccessor _httpContext;
        private readonly IUserRoleService _userRoleService;
        private readonly IRoleModulePermissionService _roleModulePermissionService;
        private readonly IPermissionService _permissionService;
        private readonly IModuleServices _moduleServices;
        private readonly IUser _user;
        private readonly IMapper _mapper;
        private readonly PermissionRequirement _permission;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="httpContext"></param>
        /// <param name="userRoleService"></param>
        /// <param name="roleModulePermissionService"></param>
        /// <param name="permissionService"></param>
        public PermissionController(IHttpContextAccessor httpContext,IUserRoleService userRoleService,
            IRoleModulePermissionService roleModulePermissionService,
            IPermissionService permissionService,IModuleServices moduleServices,IUser user,IMapper mapper,PermissionRequirement permission)
        {
            _httpContext = httpContext;
            _userRoleService = userRoleService;
            _roleModulePermissionService = roleModulePermissionService;
            _permissionService = permissionService;
            _moduleServices = moduleServices;
            _user = user;
            _mapper = mapper;
            _permission = permission;
        }

        /// <summary>
        /// 获取路由树
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<List<Permission>>> GetNavigationBar(long uid)
        {
            var data = new MessageModel<List<Permission>>();

            var rolesIds = new List<long>();
            //var auth = _httpContext?.HttpContext?.Request.Headers.Authorization;
            //var tokenStr = auth?.ObjToString().Replace("Bearer ", "");
            //var token = JwtToken.SerializeToken(tokenStr);
            //var uId = token.Uid;

            var roles = await _userRoleService.Query(d => d.IsDeleted == false && d.UserId == uid);
            var roleIds = roles.Select(d => d.RoleId.ObjToLong()).Distinct().ToList();
            if (roleIds.Any())
            {
                var pids = (await _roleModulePermissionService.Query(d => d.IsDeleted == false && roleIds.Contains(d.RoleId)))
                            .Select(d => d.PermissionId.ObjToLong()).Distinct();
                if (pids.Any())
                {
                    var rolePermissionModules = (await _permissionService.Query(i => pids.Contains(i.Id))).OrderBy(c => c.OrderSort);

                    var resData = rolePermissionModules.Where(i => i.IsDeleted == false).OrderBy(i => i.Id).ToList();

                    data.success = true;
                    data.data = resData;
                    data.message = "获取成功";

                    // var temp = rolePermissionModules.ToList().Find(t => t.Id == 87);
                    #region MyRegion
                    //var permissionTrees = rolePermissionModules.Where(i=>i.IsDeleted==false).OrderBy(i=>i.Id)
                    //    .Select(i=>new NavigationBar
                    //    {
                    //        id=i.Id,
                    //        name=i.Name,
                    //        pid=i.Pid,
                    //        order = i.OrderSort,
                    //        path=i.Code,
                    //        iconCls = i.Icon,
                    //        Func=i.Func,
                    //        IsHide=i.IsHide.ObjToBool(),
                    //        IsButton=i.IsButton.ObjToBool(),
                    //        meta=new NavigationBarMeta
                    //        {
                    //            requireAuth=true,
                    //            title=i.Name,
                    //            NoTabPage = i.IsHide.ObjToBool(),
                    //            keepAlive= i.IsKeepAlive.ObjToBool(),
                    //        }
                    //    }).ToList();

                    //NavigationBar root = new NavigationBar
                    //{
                    //    id = 0,
                    //    pid = 0,
                    //    order = 0,
                    //    name = "根节点",
                    //    path = "",
                    //    iconCls = "",
                    //    meta = new NavigationBarMeta()
                    //};

                    //permissionTrees = permissionTrees.OrderBy(d => d.order).ToList();

                    //RecursionHelper.LoopNaviBarAppendChildren(permissionTrees, root);
                    //data.success = true;
                    //data.data=root;
                    //data.message = "获取成功"; 
                    #endregion
                }
            }

            return data;
        }

        /// <summary>
        /// 获取菜单列表树
        /// </summary>
        /// <param name="parentId"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<List<Permission>>> GetTreeTable(long parentId ,string key = "")
        {
            List<Permission> permissions = new List<Permission>();
            var apiList = await _moduleServices.Query(d => d.IsDeleted == false);
            var permissionList = await _permissionService.Query(d => d.IsDeleted == false);
            if (string.IsNullOrEmpty(key))
            {
                permissions = permissionList.Where(a => a.Pid == parentId).OrderBy(i => i.OrderSort).ToList();
            }
            else
            {
                permissions = permissionList.Where(a => a.Name.Contains(key)).OrderBy(i => i.OrderSort).ToList();
            }
            foreach (var item in permissions)
            {
                List<long> pidarr = new();
                var parent = permissionList.FirstOrDefault(a => a.Id == item.Pid);
                while (parent != null)
                {
                    pidarr.Add(parent.Id);
                    parent = permissionList.FirstOrDefault(a => a.Id == parent.Pid);
                }

                pidarr.Reverse();
                pidarr.Insert(0, 0);
                item.PidArr = pidarr;
                item.MName = apiList.FirstOrDefault(i => i.Id == item.Mid)?.LinkUrl;
                item.HasChildren = permissionList.Where(i=>i.Pid==item.Id).Any();

            }

             return Success(permissions);
        }

        /// <summary>
        /// 获取菜单树
        /// </summary>
        /// <param name="parentId"></param>
        /// <param name="needbtn"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<PermissionTree>> GetPermissionTree(long parentId=0,bool needbtn = false)
        {
            var permissions = await _permissionService.Query(d => d.IsDeleted == false);
            var permissionTree = permissions.Where(i => i.IsDeleted == false).OrderBy(i => i.Id).Select(i => new PermissionTree
            {
                value = i.Id,
                label = i.Name,
                Pid = i.Pid,
                isbtn = i.IsButton,
                order = i.OrderSort
            }).ToList();

            var root = new PermissionTree
            {
                value = 0,
                Pid = 0,
                label = "根节点"
            };

            permissionTree = permissionTree.OrderBy(d => d.order).ToList();
            RecursionHelper.LoopToAppendChildren(permissionTree, root, parentId, needbtn);

            return Success(root, "获取成功");
        }

        /// <summary>
        /// 添加菜单
        /// </summary>
        /// <param name="permission"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<MessageModel<string>> Post(PermissionDto permission)
        {
            permission.CreateId = _user.UserId;
            permission.CreateBy = _user.UserName;
            var model = _mapper.Map<Permission>(permission);
            var  res = await _permissionService.Add(model);
            return res>0 ? Success(res.ToString(), "添加角色成功") : Fail("添加角色失败");
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<MessageModel<string>>Put(Permission dto)
        {
            var data = new MessageModel<string>();
            if (dto != null && dto.Id > 0)
            {
                data.success= await _permissionService.Update(dto);
                await _roleModulePermissionService.UpdateModuleId(dto.Id, dto.Mid);
                if (data.success)
                {
                    data.message = "更新成功";
                    data.data = dto.Id.ToString();
                }
            }
            return data;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<MessageModel<string>> Delete(long id)
        {
            var data = new MessageModel<string>();
            if (id > 0)
            {
                var model =await _permissionService.QueryById(id);
                model.IsDeleted = true;
                data.success =  await _permissionService.Update(model);
                if (data.success)
                {
                    data.message = "删除成功";
                    data.data = model.Id.ToString();
                }
            }
            return data;
        }

        /// <summary>
        /// 根据角色id获取该角色拥有的权限
        /// </summary>
        /// <param name="rid"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<AssignShow>> GetPermissionIdByRoleId(long rid = 0)
        {
            var rmps = await _roleModulePermissionService.Query(i => i.IsDeleted == false && i.RoleId == rid);
            var permissionTrees = (from child in rmps
                                   orderby child.Id
                                   select child.PermissionId.ObjToLong()).ToList();
            
            var permissions = await _permissionService.Query(d => d.IsDeleted == false);
            List<string> assignbtns = new List<string>();
            foreach (var item in permissionTrees)
            {
                var pername = permissions.FirstOrDefault(d => d.IsButton && d.Id == item)?.Name;
                if (!string.IsNullOrEmpty(pername))
                {
                    //assignbtns.Add(pername + "_" + item);
                    assignbtns.Add(item.ObjToString());
                }
            }

            return Success(new AssignShow()
            {
                permissionids = permissionTrees,
                assignbtns = assignbtns,
            }, "获取成功");
        }

        /// <summary>
        /// 给角色分配权限
        /// </summary>
        /// <param name="assignView"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<MessageModel<string>> Assign(AssignView assignView)
        {
            if (assignView.rid > 0)
            {
                try
                {
                    var old_rmps = await _roleModulePermissionService.Query(d => d.RoleId == assignView.rid);
                    // TODO 需要开启事务 
                    await _permissionService.Db.Deleteable<RoleModulePermission>(i => i.RoleId == assignView.rid).ExecuteCommandAsync();
                    var permissions = await _permissionService.Query(i => i.IsDeleted == false);
                    List<RoleModulePermission> new_rmps = new List<RoleModulePermission>();
                    var nowTime = _permissionService.Db.GetDate();
                    foreach (var item in assignView.pids)
                    {
                        var moduleId = permissions.Find(p => p.Id == item)?.Mid;
                        var find_old_rmps = old_rmps.Find(p => p.PermissionId == item);
                        var roleModelPermission = new RoleModulePermission()
                        {
                            IsDeleted = false,
                            RoleId = assignView.rid,
                            ModuleId = moduleId.ObjToLong(),
                            PermissionId = item,
                            CreateId = find_old_rmps == null ? _user.UserId : find_old_rmps.CreateId,
                            CreateBy = find_old_rmps==null?_user.UserName:find_old_rmps.CreateBy,
                            CreateTime = find_old_rmps==null?nowTime:find_old_rmps.CreateTime,
                            ModifyId = _user.UserId,
                            ModifyBy = _user.UserName,
                            ModifyTime = nowTime
                        };
                        new_rmps.Add(roleModelPermission);
                    }
                    if (new_rmps.Count > 0) await _roleModulePermissionService.Add(new_rmps);
                }
                catch (Exception ex)
                {

                    throw;
                }
                _permission.Permissions.Clear();
                return Success<string>("保存成功");
            }
            else
            {
                return Fail<string>("请选择要操作的角色");
            }
        }
    }
    public class AssignView
    {
        public List<long> pids { get; set; }
        public long rid { get; set; }
    }
    public class AssignShow
    {
        public List<long> permissionids { get; set; }
        public List<string> assignbtns { get; set; }
    }
}
